package com.tangyuan.common.util.iospay;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * 苹果内购验证工具类
 */
@Slf4j
public class AppleVerifyUtil {
    /**
     * 苹果内购沙盒环境
     */
    private static final String URL_SANDBOX = "https://sandbox.itunes.apple.com/verifyReceipt";
    /**
     * 苹果内购正式环境
     */
    private static final String URL_VERIFY = "https://buy.itunes.apple.com/verifyReceipt";
    /**
     * 秘钥 （自动订阅服务需要秘钥）
     */
    private static final String KEY = "需要到APP Store后台获取";


    /**
     * 苹果服务器内购验证票据
     *
     * @param receipt 验证收据
     * @param type    环境  （0 开发）
     * @return
     */
    public static String verifyApple(String receipt, int type) {
        String url = "";
        // 环境判断 线上/开发环境用不同的请求链接
        if (type == 0) {
            url = URL_SANDBOX;
        } else {
            url = URL_VERIFY;
        }

        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("receipt-data", receipt);
            // jsonObject.put("password", KEY);

            String result = HttpUtil.post(url, jsonObject.toString());
            return result;
            // return okHttpClient.newCall(request).execute().body().string();
        } catch (Exception e) {
            log.error("[票据校验失败！]");
            return null;
        }
    }

    private static class TrustAnyTrustManager implements X509TrustManager {

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[]{};
        }
    }
}

